import { RandUtil } from "../../util/RandUtil";
import BaseAI, { IBaseAI } from "./BaseAI";
import Food from "../../world/Food";

const ru = RandUtil

export interface IAIEat extends IBaseAI {
    findDis: number | [number, number]
    /** 食物数量少于多少就更新寻找组 (默认0.75)*/
    foodLessUpdate?: number | [number, number]
}

export default class AIEat extends BaseAI {

    private _findDisArr: number[]
    private _foodLessUpdateArr: number[]
    private _findDis: number
    private _foodLessUpdate: number
    private _foods: Food[]
    private _foodMin: number
    private _food: Food

    constructor(obj: IAIEat) {
        super(obj)
        this._findDisArr = this.toMinMax(obj.findDis)
        this._foodLessUpdateArr = this.toMinMax(obj.foodLessUpdate || 0.75)
    }

    getKey(): string { return "ai_eat" }

    aiStart() {
        let head = this.head
        this._findDis = ru.rand2(this._findDisArr) * head.w + head.w
        this._foodLessUpdate = ru.rand2(this._foodLessUpdateArr)
        this.updateFindFoods()
    }

    ai(dt: number): void {

        if (!this._foods || this._foods.length < this._foodMin) {
            this.updateFindFoods()
        }

        while (!this._food) {
            if (this._foods.length) {
                let food = this._foods.shift()
                if (food.isLive) {
                    this._food = food
                }
            } else {
                this._foods = null
                break
            }

        }

        if (this._food) {
            if (this._food.isLive) {
                let head = this.head
                head.toAng = head.angTo(this._food)
            } else {
                this._food = null
            }
        }

    }

    aiStop() {
        this._foods = this._food = null
    }

    private updateFindFoods() {
        let head = this.snake.head
        let findCol = head.cp().setW(this._findDis)
        let chunks = this.world.getChunks(findCol)
        this._foods = this.world.getFoods(chunks).sort((f1, f2) => {
            let d1 = findCol.dis(f1)
            let d2 = findCol.dis(f2)
            return d1 - d2
        })
        this._foodMin = this._foods.length * this._foodLessUpdate
    }
}